/*
 * CTCPServer.cpp
 *
 *  Created on: 05.03.2012
 *      Author: caffeine
 */
#include "CTCPServer.h"
#include "CTCPClient.h"
#include <stdio.h>
#include <lampe/network/IServerCallBack.h>
#include <lampe/exception/Network.h>


namespace lampe{
namespace network{


CTCPServer::CTCPServer(IServerCallBack*callback):CServer(callback){
	//nothing
}

void CTCPServer::waitClient(){
	while (server!=0){

		SOCK_ADDRESS addr;
		SOCKET s=do_accept(server,&addr);
		if (s<=0){
			return;
		}
		IClientCallback*cbl=getClientObject();
		if (!cbl){
			do_close_socket(s);
		}else{
			CTCPClient*c=new CTCPClient(cbl);
			c->setConnect(&s);
			cbl->drop();
		}
	}
}

bool CTCPServer::onStart(){
	loadNetworkLib();
	server=create_server_socket();
	addr=create_address();
	set_port(addr,(int)serverport);
	set_host_any(addr);
	if (!do_bind(server,addr)){
		GEN_NETWORK_ERROR(lampe::str::format("TCP server: Can't bind server port %u",serverport));
		return false;
	}
	
	if (!do_listen(server)){
		GEN_NETWORK_ERROR("TCP server: Can't start listen");
		return false;
	}
	return true;
}

void CTCPServer::onStop(){
	do_close_socket(server);
	server=0;
}

void CTCPServer::port(u32 p){
	serverport=p;
}

u32 CTCPServer::port(){
	return serverport;
}

CTCPServer::~CTCPServer(){
}

extern ITCPServer*createTCPServer(IServerCallBack*callback){
	return new CTCPServer(callback);
}

}//namespace network
}//namespace lampe
